package com.example.book.controller.user;

import com.example.book.context.BaseContext;
import com.example.book.dto.BookDTO;
import com.example.book.dto.BookPageDTO;
import com.example.book.dto.BorrowPageDTO;
import com.example.book.dto.UserDTO;
import com.example.book.entity.Borrow;
import com.example.book.entity.User;
import com.example.book.result.PageResult;
import com.example.book.service.impl.admin.BookService;
import com.example.book.service.impl.user.UserService;
import com.example.book.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.security.auth.login.AccountNotFoundException;
import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private TokenUtil tokenUtil;
    //用户登录
    @PostMapping("/login")
    public String login(@RequestBody UserDTO userDTO) throws AccountNotFoundException {
        log.info("用户信息：{}",userDTO);
        String role = "ROLE_ADMIN";
        String token = tokenUtil.getUserToken(userDTO.name,role);
        userService.login(userDTO);
        return "UserToken:"+token;
    }
    //用户注册
    @PostMapping("/register")
    public String register(@RequestBody User user) throws AccountNotFoundException {
        log.info("注册的用户信息：{}",user);
        userService.insert(user);
        return "注册成功";
    }
    //图书借阅
    @PostMapping("/borrow")
    public String borrow(@RequestParam List <String> bookName ) throws AccountNotFoundException {
        log.info("要借的书的信息：{}",bookName);
        userService.borrowByBookName(bookName);
        return "借阅成功";
    }
    //显示已经借到的书
    @GetMapping("/page")
    public List<PageResult> page(BorrowPageDTO borrowPageDTO){
        log.info("要请求的页码数据：{}",borrowPageDTO);
        PageResult pageResult = userService.borrowBook(borrowPageDTO);
        return pageResult.getRecords();
    }
    //图书的归还
    @PostMapping("/return")
    public String giveBook(@RequestParam List <String> bookName){
        log.info("要归还的书籍名称：{}",bookName);
        userService.giveBook(bookName);
        return "归还成功";
    }
}
